package com.ntd.study.protocol.socket;

import ntd.util.UtilArray;
import ntd.util.UtilThreadPool;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

@Slf4j
public class UtilSocketClient implements UtilCollectInterface {
    private String host;
    private int prot;
    private Socket socket;

    public UtilSocketClient(String host, int prot) {
        this.host = host;
        this.prot = prot;
        try {
            init();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws UnknownHostException, IOException {
        final UtilSocketClient utilSocketClient = new UtilSocketClient("127.0.0.1", 32222);
        utilSocketClient.sendMsg("测试发送消息".getBytes());
//        utilSocketClient.close();
    }

    /**
     * 初始化
     * @throws IOException
     */
    private void init() throws IOException {
        socket = new Socket(host, prot);
        InputStream is = socket.getInputStream();
        UtilThreadPool.scheduledThreadPool.execute(() -> {
            //接收服务器端反馈
            try {
                final byte[] bytes = new byte[1024];
                int len;
                while(true){
                    if(is.available() < 1){
                        continue;
                    }
                    len = is.read(bytes);
                    if(len != -1){
                        log.info("传入数据：" + new String(bytes));
                        onMsg(UtilArray.removeLeZero(bytes));
                    }
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 发送消息
     * @param msg
     */
    @Override
    public void sendMsg(byte[] msg) {
        OutputStream outputStream = null;
        try {
            if(socket.isClosed()){
                init();
            }
            outputStream = socket.getOutputStream();
            outputStream.write(msg);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

        }
    }

    /**
     * 关闭连接
     */
    public void close(){
        if(socket != null){
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void onMsg(byte[] b){
        log.info(new String(b));
    }


}
